//
//  SubjectViewController.m
//  NineGroupProject
//
//  Created by dllo on 15/12/22.
//  Copyright © 2015年 lushan. All rights reserved.
//

#import "SubjectViewController.h"
#import <Masonry.h>
#import <UIImageView+WebCache.h>
#import "LSSubjDetailCell.h"
#import "LSAppTools.h"
#import "SubjectModel.h"
#import "LSSubjDetailViewController.h"
#import <MJRefresh.h>
@interface SubjectViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView *subjTableView;
@property (nonatomic, strong)UIView *headerView;
@property (nonatomic, strong)UIScrollView *scrollView;
@property (nonatomic, strong)UIPageControl *pageC;
@property (nonatomic, strong)UIImageView *image;
@property (nonatomic, retain)NSMutableArray *scArray;
@property (nonatomic, strong)NSTimer *timer;

@property (nonatomic, strong)NSMutableArray *TVArray;
@property (nonatomic, assign)NSInteger page;

@property (nonatomic, assign)BOOL isLoad;

@end

@implementation SubjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _scArray = [NSMutableArray array];
    _TVArray = [NSMutableArray array];
    _page = 1;
    UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectZero];
    [customLab setTextColor:[UIColor whiteColor]];
    [customLab setText:@"专题"];
    customLab.textAlignment = NSTextAlignmentCenter;
    customLab.font = [UIFont boldSystemFontOfSize:20];
    [customLab sizeToFit];
    self.navigationItem.titleView = customLab;
    
    _subjTableView = [[UITableView alloc] init];
    _subjTableView.delegate = self;
    _subjTableView.dataSource = self;
    _subjTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_subjTableView registerClass:[LSSubjDetailCell class] forCellReuseIdentifier:@"LSSubjDetailCell"];
    [self.view addSubview:_subjTableView];
    [_subjTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 200 * HEIGHT/667)];
//    self.headerView.backgroundColor = [UIColor redColor];
    self.subjTableView.tableHeaderView = self.headerView;
    
    
    [self getData];
    NSString *url = @"http://api.daizhe.cn/v3/experience/?device_type=3&device_code=867031028257589&dz_token=&device_token=6f293dd63ecd21fca52624dcc239abb1&ac=jingxuan&dz_uid=&current_date=1450701192419&page=1&cur_version=2.2&dz_channel=meizu";
    [self getTableViewData:url];
    [self addHeader];
    [self addFooter];
    
    
}

- (void)createHeadView{

    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.backgroundColor = [UIColor lightGrayColor];
    self.scrollView.contentSize = CGSizeMake(WIDTH * (self.scArray.count + 2), 0);
    self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
    //设置按页滚动
    self.scrollView.pagingEnabled = YES;
        self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.bounces = NO;
    self.scrollView.tag = 1000;
    [self.headerView addSubview:self.scrollView];
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.equalTo(self.headerView.mas_right).offset(0);
        make.top.mas_equalTo(0);
        make.height.equalTo(self.headerView.mas_height);
    }];
    
    NSMutableArray *arr = [NSMutableArray arrayWithObject:[self.scArray lastObject]];
    for (int i = 0; i < self.scArray.count; i++) {
        [arr addObject: [self.scArray objectAtIndex:i]];
    }
    [arr addObject:[self.scArray firstObject]];
    NSLog(@"--%ld",arr.count);
    //添加6张图片
    for (int i = 0 ;  i  < arr.count; i++) {
        
        self.image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"placeholderImag.png"]];
        NSURL *urls = [NSURL URLWithString:[arr objectAtIndex:i]];
        [self.image sd_setImageWithURL:urls placeholderImage:[UIImage imageNamed:@"placeholderImag.png"]];
        [self.scrollView addSubview:self.image];
        [self.image mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0 + i * WIDTH);
            make.width.mas_equalTo(WIDTH);
            make.top.mas_equalTo(0);
            make.height.equalTo(self.scrollView.mas_height);
        }];
    }
    
    self.scrollView.delegate = self;
    //设置页面
    self.pageC = [[UIPageControl alloc]init];
    self.pageC.backgroundColor = [UIColor clearColor];
    [self.headerView addSubview:self.pageC];
    
    [self.pageC mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(100);
        make.right.mas_equalTo(-100);
        make.bottom.mas_equalTo(-10);
        make.height.mas_equalTo(20);
    }];
    
    //设置页码数
    self.pageC.numberOfPages = self.scArray.count;
    //设置选中页码的颜色
    self.pageC.currentPageIndicatorTintColor = [UIColor whiteColor];
    //设置未选中的页码颜色
    self.pageC.pageIndicatorTintColor = [UIColor grayColor];
    //设置当前选中页
    self.pageC.currentPage = 0;
    [self addTimer];
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == self.scrollView) {
        
        if (scrollView.contentOffset.x == 0) {
            // 用户滑动到1号位置，此时必须跳转到倒二的位置
            [scrollView setContentOffset:CGPointMake(WIDTH * (self.scArray.count), 0) animated:NO];
        }
        else if (scrollView.contentOffset.x == scrollView.contentSize.width - WIDTH) {
            
            [scrollView setContentOffset:CGPointMake(WIDTH, 0) animated:NO];
            
        }
        self.pageC.currentPage = scrollView.contentOffset.x / WIDTH - 1;
    }
}
//开始拖拽的时候调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //关闭定时器(注意,定时器一旦被关闭,无法在开启)
    [self removeTimer];
}
//拖拽结束后
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self addTimer];
}
//开启定时器
- (void)addTimer{
    //设置定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(change:) userInfo:nil repeats:YES];
    
}

- (void)change:(NSTimer *)time{
    if (self.pageC.currentPage == self.pageC.numberOfPages - 1) {
        self.pageC.currentPage = 0;
    } else if (self.pageC.currentPage < self.pageC.numberOfPages - 1) {
        self.pageC.currentPage++;
    }
    [self.scrollView setContentOffset:CGPointMake((self.pageC.currentPage + 1) * WIDTH, 0) animated:YES];
}

//关闭定时器
- (void)removeTimer{
    if (_timer) {
        if ([self.timer isValid]) {
            [self.timer invalidate];
            _timer=nil;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _TVArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LSSubjDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LSSubjDetailCell"];
    cell.subTVM = [self.TVArray objectAtIndex:indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150 * HEIGHT / 667;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CATransition *transition = [CATransition animation];
    transition.duration = 0.7f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = @"cube";
    transition.subtype = kCATransitionFromRight;
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    LSSubjDetailViewController *lsSubDetail = [[LSSubjDetailViewController alloc] init];
    lsSubDetail.subTVM = [_TVArray objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:lsSubDetail animated:YES];
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    // 添加上拉刷新尾部控件

    self.subjTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _isLoad = NO;
        self.page++;
        NSString *url = [NSString stringWithFormat:@"http://api.daizhe.cn/v3/experience/?device_type=3&device_code=867031028257589&dz_token=&device_token=6f293dd63ecd21fca52624dcc239abb1&ac=jingxuan&dz_uid=&current_date=1450701192419&page=%ld&cur_version=2.2&dz_channel=meizu", self.page];
        NSLog(@"上拉");
        [self getTableViewData:url];//请求数据
        [_subjTableView.footer endRefreshing];
    }];
    
}
#pragma mark --下拉刷新
- (void)addHeader{
    self.subjTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _isLoad = YES;
        NSString *url = @"http://api.daizhe.cn/v3/experience/?device_type=3&device_code=867031028257589&dz_token=&device_token=6f293dd63ecd21fca52624dcc239abb1&ac=jingxuan&dz_uid=&current_date=1450701192419&page=1&cur_version=2.2&dz_channel=meizu";
        NSLog(@"下拉");
        [self getTableViewData:url];//请求数据
        [self getData];
        [_subjTableView.header endRefreshing];
    }];
}
- (void)getData{
    [_scArray removeAllObjects];
    //http://api.liwushuo.com/v2/banners
    NSString *url = @"http://api.liwushuo.com/v2/banners";
    [LSAppTools getDataWithURL:url blcok:^(id result) {
        if (_isLoad == YES) {
            [self.scrollView removeFromSuperview];
            [self.scArray removeAllObjects];
            [self.pageC removeFromSuperview];
            [self removeTimer];
        }
        //        NSLog(@"result= %@",result);
        NSMutableDictionary *dataDic = [result objectForKey:@"data"];
        NSMutableArray *bannersArr = [dataDic objectForKey:@"banners"];
        for (NSMutableDictionary *smallDic in bannersArr) {
            SubjectModel *subM = [[SubjectModel alloc] init];
            [subM setValuesForKeysWithDictionary:smallDic];
            [_scArray addObject:subM.image_url];
        }
        NSLog(@"%ld",_scArray.count);
        [_subjTableView reloadData];
            [self createHeadView];
    }];
    
}

- (void)getTableViewData:(NSString *)url{
    
    [LSAppTools getDataWithURL:url blcok:^(id result) {
        if (_isLoad == YES) {
            [self.TVArray removeAllObjects];
        }
//       NSLog(@"result= %@",result);
        NSMutableDictionary *responseDataDic = [result objectForKey:@"responseData"];
        NSMutableArray *listArr = [responseDataDic objectForKey:@"list"];
        for (NSMutableDictionary *smallDic in listArr) {
            SubjTVModel *subTVM = [[SubjTVModel alloc] init];
            [subTVM setValuesForKeysWithDictionary:smallDic];
            [self.TVArray addObject:subTVM];
        }
        [_subjTableView reloadData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
